package org.x.commonmod;

import cn.idev.excel.converters.Converter;
import cn.idev.excel.metadata.GlobalConfiguration;
import cn.idev.excel.metadata.data.ReadCellData;
import cn.idev.excel.metadata.data.WriteCellData;
import cn.idev.excel.metadata.property.ExcelContentProperty;

import java.util.Arrays;

public class GlobalEnumConverter implements Converter<DescEnum> {

    @Override
    public Class<DescEnum> supportJavaTypeKey() {
        return DescEnum.class;
    }

    @Override
    public WriteCellData<?> convertToExcelData(DescEnum value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (value == null) return new WriteCellData<>("");
        return new WriteCellData<>(value.getDesc());
    }

    @Override
    @SuppressWarnings("unchecked")
    public DescEnum convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        Class<? extends DescEnum> enumClass = (Class<? extends DescEnum>) contentProperty.getField().getType();

        return Arrays.stream(enumClass.getEnumConstants())
                .filter(e -> e.getDesc().equals(cellData.getStringValue()))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("枚举转换失败: " + cellData.getStringValue()));
    }
}
